﻿using FourWayClimbingDemo.Chess.Rule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FourWayClimbingDemo.Chess
{
    /// <summary>
    /// 裁判
    /// </summary>
    public class Referee
    {
        private ChessBoard _chessBoard;
        private Player _player1;
        private Player _player2;
        private Player _currentPlayer;

        public Referee(ChessBoard chessBoard, Player player1, Player player2) {
            this._chessBoard = chessBoard;
            this._player1 = player1;
            this._player2 = player2;
            this._currentPlayer = player1;
        }

        /// <summary>
        /// 轮到对方选手执棋
        /// </summary>
        private void NextPlayer() {
            if (ReferenceEquals(_currentPlayer, _player1))
            {
                _currentPlayer = _player2;
            }
            else {
                _currentPlayer = _player1;
            }   
        }

        /// <summary>
        /// 当前执棋选手
        /// </summary>
        public Player CurrentPlayer
        {
            get { return _currentPlayer; }
        }

        /// <summary>
        /// 移动棋子
        /// </summary>
        public Boolean MoveChessPiece(int row,int col,Dir dir) {
            var chessPiece = _currentPlayer.GetChessPiece(row,col);
            if (chessPiece == null) return false;
            return MoveChessPiece(chessPiece,dir);
        }

        public Boolean MoveChessPiece((int row, int col) pos, Dir dir)
        {
            var chessPiece = _currentPlayer.GetChessPiece(pos.row, pos.col);
            if (chessPiece == null) return false;
            return MoveChessPiece(chessPiece, dir);
        }

        /// <summary>
        /// 移动棋子
        /// </summary>
        public Boolean MoveChessPiece(ChessPiece chessPiece, Dir dir)
        {
            var rule = new MoveChessPieceRule(_chessBoard, _currentPlayer, chessPiece, dir);
            if (rule.Execute()) {
                NextPlayer();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 判断选手输赢
        /// </summary>
        public Player GetWinner() {
            var rule1 = new LostRule(_player1);
            if (rule1.Execute()) return _player2;
            var rule2 = new LostRule(_player2);
            if (rule2.Execute()) return _player1;
            return null;
        }

        /// <summary>
        /// 重新开始游戏
        /// </summary>
        public void ReStart() {
            _player1.ReInitChessPieces();
            _player2.ReInitChessPieces();
            _currentPlayer = _player1;
        }

    }

    /// <summary>
    /// 方向枚举
    /// </summary>
    public enum Dir
    {
        LEFT = 1,
        RIGHT = 2,
        TOP = 3,
        BOTTOM = 4,
    }

}
